<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>金额大小写转换</title>
		<style>
			body {
				font-family: "微软雅黑";
			}

			.blue {
				color: blue;
			}

			.red {
				color: red;
			}
		</style>
	</head>
	<body>
		<div>
			<input type="text" id="InputNum" placeholder="请输入金额">
			<button onclick="convertAmount()">转换</button>
			<div>
				<span>银行金额：</span>
				<span id="bankAmount"></span>
			</div>
			<div>
				<span>大写金额：</span>
				<span id="uppercaseAmount"></span>
			</div>
		</div>

		<script>
			function convertAmount() {
				var inputAmount = document.getElementById("InputNum").value.trim(); //trim()可去除首尾空白字符

				if (inputAmount == "") {
					alert("请输入金额");
					return;
				}

				var regex = /^(\d{1,13})(?:\.(\d{1,}))?$/;
				if (!regex.test(inputAmount)) {
					alert("金额格式不正确");
					return;
				}

				var processedAmount = parseFloat(inputAmount).toFixed(2);

				var bankAmount = processedAmount.replace(/\B(?=(\d{3})+(?!\d))/g, ",");

				var uppercaseAmount = numToCny(processedAmount);

				document.getElementById("bankAmount").textContent = bankAmount;
				document.getElementById("uppercaseAmount").innerHTML = uppercaseAmount;
			}

			function numToCny(num) {
				var counts = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
				var strOutput = "";
				var strUnit = ["仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"];
				num += "00";
				var intPos = num.indexOf('.');
				if (intPos >= 0) {
					num = num.substring(0, intPos) + num.substr(intPos + 1, 2);
				}
				var neededUnits = strUnit.slice(-num.length);
				for (var i = 0; i < num.length; i++) {
					var digit = num.substr(i, 1);
					strOutput += '<span class="red">' + counts[parseInt(digit)] + '</span>';
					strOutput += '<span class="blue">' + neededUnits[i] + '</span>';
				}
				return strOutput.replace(/零角零分$/, '整').replace(/零[仟佰拾]/g, '零').replace(/零{2,}/g, '零').replace(/零(?=元|万|亿)/g, '');
			}
		</script>
	</body>
</html>